package com.sc.highspeed.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sc.highspeed.controller.result.JsonResult;
import com.sc.highspeed.db.model.UserGroupModel;
import com.sc.highspeed.db.model.UserMenuModel;
import com.sc.highspeed.db.model.UserModel;
import com.sc.highspeed.service.OrganizationService;
import com.sc.highspeed.service.UserGroupService;
import com.sc.highspeed.service.UserMenuService;
import com.sc.highspeed.service.UserService;
import com.sc.highspeed.tools.MD5Tool;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Admin on 2017/11/27.
 */
@Api(value = "用户管理接口", description = "用户管理接口")
@Controller
@RequestMapping("/userManage")
public class UserManagerController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserGroupService userGroupService;

    @Autowired
    private UserMenuService userMenuService;

    @Autowired
    private OrganizationService organizationService;

    private static final Logger login = Logger.getLogger("login");

    /**
     * 获取所有用户
     * @return
     */
    @RequestMapping(value = "/getUserList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户列表",httpMethod = "GET",
            response = JsonResult.class, notes = "")
    public List<UserModel> getUserList() {
        return userService.getUserList();
    }

    /**
     * 获取用户
     * @param number
     * @return
     */
    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "通过用户编号获取用户",httpMethod = "GET",
            response = JsonResult.class, notes = "")
    public JsonResult getUserByNumber(@ApiParam(value = "用户编号") @RequestParam String number) {
        JsonResult result = new JsonResult();
        List list = new ArrayList();
        String username = "";
        UserModel userModel = userService.getUserByNumber(number);
        if (userModel != null) {
            username = userModel.getUsername();
            list.add(userModel);
            list.add(userMenuService.getUserMenuByUsername(username));
            result.setCode(1);
            result.setStatus(true);
            result.setObject(list);
        } else {
            result.setCode(0);
            result.setStatus(false);
            result.setMsg("该用户不存在！");
        }

        return result;
    }

//    /**
//     * 删除用户
//     * @param map
//     * @return
//     */
//    @RequestMapping("/deleteUser")
//    @ResponseBody
//    public List<JsonResult> deleteUser(@RequestBody Map<String, Object> map) {
//        List<JsonResult> results = new ArrayList<JsonResult>();
//        JsonResult result = new JsonResult();
//        String name = "";
//        String username = "";
//        ArrayList<String> numbers = (ArrayList<String>) map.get("numbers");
//        for (String number : numbers) {
//            if (userService.getUserByNumber(number) != null) {
//                if (userService.deleteUserByNumber(number) == 1) {
//                    username = userService.getUserByNumber(number).getUsername();
//                    userMenuService.deleteUserMenuByUsername(username);
//                    result.setCode(1);
//                    result.setStatus(true);
//                } else {
//                    name = userService.getUserByNumber(number).getName();
//                    result.setCode(0);
//                    result.setStatus(false);
//                    result.setMsg(name + "删除失败！");
//                }
//            } else {
//                result.setCode(-1);
//                result.setStatus(false);
//                result.setMsg("用户不存在！");
//            }
//
//            results.add(result);
//        }
//        return results;
//    }
//    @RequestMapping("/deleteUser")
//    @ResponseBody
//    public JsonResult deleteUser(@RequestParam String number) {
//        JsonResult result = new JsonResult();
//        if (userService.getUserByNumber(number) != null) {
//            String username = userService.getUserByNumber(number).getUsername();
//            userMenuService.deleteUserMenuByUsername(username);
//            int code = userService.deleteUserByNumber(number);
//            if (code == 1) {
//                result.setCode(1);
//                result.setStatus(true);
//            } else {
//                result.setCode(0);
//                result.setStatus(false);
//                result.setMsg("删除失败！");
//            }
//        } else {
//            result.setCode(-1);
//            result.setStatus(false);
//            result.setMsg("该用户不存在！");
//        }
//
//        return result;
//    }

//    /**
//     * 添加用户
//     * @param userModel
//     * @return
//     */
//    @RequestMapping("/insertUser")
//    @ResponseBody
//    public JsonResult insertUser(@RequestBody UserModel userModel) {
//        JsonResult result = new JsonResult();
//        if (userService.getUserByNumber(userModel.getNumber()) != null) {
//            int code = userService.insertUser(userModel);
//            if (code == 1) {
//                result.setCode(1);
//                result.setStatus(true);
//            } else {
//                result.setCode(0);
//                result.setStatus(false);
//                result.setMsg("添加失败！");
//            }
//        } else {
//            result.setCode(-1);
//            result.setStatus(false);
//            result.setMsg("该用户已存在！");
//        }
//
//        return result;
//    }

    /**
     * 更新用户
     * @param map
     * @return
     */
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "更新用户",httpMethod = "POST",
            response = JsonResult.class, notes = "")
    public JsonResult updateUser(@ApiParam(value = "用户实体(user)，权限数组(menus)") @RequestBody Map<String, Object> map) throws IOException {
        JsonResult result = new JsonResult();
        ObjectMapper mapper = new ObjectMapper();
        UserMenuModel userMenuModel = new UserMenuModel();
        String json = mapper.writeValueAsString(map.get("user"));
        UserModel userModel = mapper.readValue(json,UserModel.class);
        String username = userModel.getUsername();
        List<Integer> menus = (ArrayList<Integer>) map.get("menus");
        if (userModel.getType().equals("管理员")) {
            if (menus.contains(16) || menus.contains(20)) {
                organizationService.updateOrganizationIsCheckByName(userModel.getOrganization(), "是");
            } else {
                organizationService.updateOrganizationIsCheckByName(userModel.getOrganization(), "否");
            }
        }
        userMenuService.deleteUserMenuByUsername(username);
        for (int menu : menus) {
            userMenuModel.setUsername(username);
            userMenuModel.setMenuId(menu);
            userMenuService.insertUserMenu(userMenuModel);
        }
        int code = userService.updateUserByUsername(userModel);
        if (code == 1) {
            result.setCode(1);
            result.setStatus(true);
        } else {
            result.setCode(0);
            result.setStatus(false);
            result.setMsg("更新失败！");
        }

        return result;
    }

//    /**
//     * 获取用户组
//     * @param name
//     * @return
//     */
//    @RequestMapping(value = "/getUserGroup", method = RequestMethod.GET)
//    @ResponseBody
//    public JsonResult getUserGroupByName(@RequestParam String name) {
//        JsonResult result = new JsonResult();
//        UserGroupModel userGroupModel = userGroupService.getUserGroupByName(name);
//        if (userGroupModel != null) {
//            result.setObject(userGroupModel);
//        } else {
//            result.setCode(0);
//            result.setStatus(false);
//            result.setMsg("该用户组不存在！");
//        }
//        return result;
//    }
//
//    /**
//     * 获取所有用户组
//     * @return
//     */
//    @RequestMapping(value = "/getUserGroupList", method = RequestMethod.GET)
//    @ResponseBody
//    public List<UserGroupModel> getUserGroupList() {
//        return userGroupService.getUserGroupList();
//    }

    /**
     * 添加用户组
     * @param userGroupModel
     * @return
     */
    @RequestMapping(value = "/insertUserGroup", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "添加用户组",httpMethod = "POST",
            response = JsonResult.class, notes = "")
    public JsonResult insertUserGroup(@ApiParam(value = "用户组实体") @RequestBody UserGroupModel userGroupModel) {
        JsonResult result = new JsonResult();
        if (userGroupService.getUserGroupByName(userGroupModel.getGroupName()) == null || userGroupService.getUserGroupByName(userGroupModel.getGroupName()).getOrganization() != userGroupModel.getOrganization()) {
            int code = userGroupService.insertUserGroup(userGroupModel);
            if (code == 1) {
                result.setCode(1);
                result.setStatus(true);
            } else {
                result.setCode(0);
                result.setStatus(false);
                result.setMsg("添加失败！");
            }
        } else {
            result.setCode(-1);
            result.setStatus(false);
            result.setMsg("该用户组已存在！");
        }
        return result;
    }

//    /**
//     * 更新用户组
//     * @param userGroupModel
//     * @return
//     */
//    @RequestMapping("/updateUserGroup")
//    @ResponseBody
//    public JsonResult updateUserGroupByName(@RequestBody UserGroupModel userGroupModel) {
//        JsonResult result = new JsonResult();
//        int code = userGroupService.updateUserGroupByName(userGroupModel);
//        if (code == 1) {
//            result.setCode(1);
//            result.setStatus(true);
//
//        } else {
//            result.setCode(0);
//            result.setStatus(false);
//            result.setMsg("更新失败！");
//        }
//        return result;
//    }

    /**
     * 删除用户组
     * @param map
     * @return
     */
    @RequestMapping(value = "/deleteUserGroup", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "批量删除用户组",httpMethod = "POST",
            response = JsonResult.class, notes = "")
    public List<JsonResult> deleteUserGroupByName(@ApiParam(value = "用户组id数组(ids)") @RequestBody Map<String, Object> map) {
        List<JsonResult> results = new ArrayList<JsonResult>();
        int code = 0;
        String userGroup = "";
        String number = "";
        String organization = "";
        List<Integer> ids = (ArrayList<Integer>)map.get("ids");
        List<String> userIds = new ArrayList<String>();
        for (int id : ids) {
            JsonResult result = new JsonResult();
            UserGroupModel userGroupModel = userGroupService.getUserGroupById(id);
            userGroup = userGroupModel.getGroupName();
            organization = userGroupModel.getOrganization();
            userGroupService.deleteUserGroupByName(id);
            if (!userService.getUserListByGroupAndOrg(userGroup, organization).isEmpty()) {
                List<UserModel> userModels =  userService.getUserListByGroupAndOrg(userGroup, organization);
                for (UserModel userModel : userModels) {
                    number = userModel.getNumber();
                    userService.updateUserGroupByNumber("",number);
                    userIds.add(userModel.getUsername());
                }
                result.setCode(-1);
                result.setStatus(false);
                result.setObject(userIds);
            } else {
                result.setCode(1);
                result.setStatus(true);
            }
            results.add(result);
        }
        return results;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "登录",httpMethod = "POST",
            response = JsonResult.class, notes = "登录成功返回该用户信息以及用户权限列表")
    public JsonResult login(@ApiParam(value = "用户名") @RequestParam String username, @ApiParam(value = "密码") @RequestParam String password) {
        JsonResult result = new JsonResult();
        List list = new ArrayList();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            result.setCode(-1);
            result.setStatus(false);
            result.setMsg("用户名或密码不能为空！");
            return result;
        }

        UserModel userModel = userService.getUserByUsername(username);
        if (userModel == null) {
            result.setCode(-1);
            result.setStatus(false);
            result.setMsg("该用户不存在！");
            return result;
        } else {
            String userPassword = userModel.getPassword();
//            String md5Password = "";
//            try {
//                md5Password = MD5Tool.md5Encode(password);
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//            if (!userPassword.equals(md5Password)) {
//                result.setCode(-1);
//                result.setStatus(false);
//                result.setMsg("用户名或密码不正确！");
//            }

            if (!userPassword.equals(password)) {
                result.setCode(-1);
                result.setStatus(false);
                result.setMsg("用户名和密码不正确！");
                return result;
            }
        }

        result.setCode(1);
        result.setStatus(true);
        result.setMsg("登录成功！");
        list.add(userModel);
        list.add(userMenuService.getUserMenuByUsername(username));
        result.setObject(list);
        login.info("用户名：" + username + "用户姓名：" + userModel.getName() + "登录");
        return result;
    }

    @RequestMapping(value = "/createUser", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "创建用户",httpMethod = "POST",
            response = JsonResult.class, notes = "")
    public JsonResult createUser(@ApiParam(value = "用户实体(user), 权限数组(menus)") @RequestBody Map<String, Object> map) throws IOException {
        JsonResult result = new JsonResult();
        ObjectMapper mapper = new ObjectMapper();
        UserMenuModel userMenuModel = new UserMenuModel();
        String json = mapper.writeValueAsString(map.get("user"));
        UserModel userModel = mapper.readValue(json,UserModel.class);
        List<Integer> menus = (List<Integer>) map.get("menus");
        userMenuModel.setUsername(userModel.getUsername());
        userModel.setType("普通用户");

        for (int menu : menus) {
            userMenuModel.setMenuId(menu);
            userMenuService.insertUserMenu(userMenuModel);
        }
        if (userService.getUserByNumber(userModel.getNumber()) == null && userService.getUserByUsername(userModel.getUsername()) == null) {
            int code = userService.insertUser(userModel);
            if (code == 1) {
                result.setCode(1);
                result.setStatus(true);
            } else {
                result.setCode(0);
                result.setStatus(false);
                result.setMsg("创建失败！");
            }
        } else {
            result.setCode(-1);
            result.setStatus(false);
            result.setMsg("该用户已存在！");
        }
        return result;
    }

//    @RequestMapping("/getUserListByGroup")
//    @ResponseBody
//    public List<UserModel> getUserListByGroupAndOrg(@RequestParam String groupName) {
//        return userService.getUserListByGroupAndOrg(groupName);
//    }

    @RequestMapping(value = "/getUserGroupListByOrg", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取指定机构下的用户组",httpMethod = "GET",
            response = JsonResult.class, notes = "")
    public List<UserGroupModel> getUserGroupListByOrg(@ApiParam(value = "机构名") @RequestParam String organization) {
        return userGroupService.getUserGroupListByOrg(organization);
    }

    @RequestMapping(value = "/deleteUsers", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "批量删除用户",httpMethod = "POST",
            response = JsonResult.class, notes = "")
    public List<JsonResult> deleteUsers(@ApiParam(value = "用户名数组(usernames)") @RequestBody Map<String, Object> map) {
        List<JsonResult> results = new ArrayList<JsonResult>();
        List<String> usernames = (ArrayList<String>) map.get("usernames");
        int code = 0;
        for (String username : usernames) {
            code = userService.deleteUserByUsername(username);
            JsonResult result = new JsonResult();
            if (code == 1) {
                result.setCode(1);
                result.setStatus(true);
            } else {
                result.setCode(0);
                result.setStatus(false);
                result.setMsg("删除失败！");
            }

            results.add(result);
        }
        return results;
    }

}
